package org.l.qiao.util;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by 严秋旺 on 2015/8/8.
 */
public class JSONConvert {

    /**
     * 将json格式的字符串转换为Map对象
     *
     * @param source json格式的字符串,例：{'key1':'value1','key2':[3,'3']}
     * @return Map对象
     */
    public static Map toMap(String source) {
        JSONObject jsonObject = new JSONObject(source);
        return toMap(jsonObject);
    }

    /**
     * 将JSONObject对象转换为Map对象，子对象也将转换。若子对象为JSONArray类型，将会转换为List对象
     *
     * @param jsonObject JsonArray对象
     * @return Map对象
     */
    public static Map toMap(JSONObject jsonObject) {
        Map<String, Object> map = new HashMap<>();
        Iterator keys = jsonObject.keys();

        while (keys.hasNext()) {
            String key = (String) keys.next();
            Object object = jsonObject.opt(key);

            if (object == JSONObject.NULL) {
                object = null;
            } else if (object instanceof JSONObject) {
                object = toMap((JSONObject) object);
            } else if (object instanceof JSONArray) {
                object = JSONArrayConvert.toList((JSONArray) object);
            }

            map.put(key, object);
        }

        return map;
    }
}
